import { baseURL } from "./env";
import { Base64 } from "js-base64";

//获取加密之后的token方法
const getToken = () => {
  //获取token
  const token = uni.getStorageSync("wxuser").user_Token || "";
  //拼接冒号
  const strToken = token + ":";
  //加密
  const encodeToken = Base64.encode(strToken);
  return "Basic " + encodeToken;
};

//定义请求参数的接口
interface httpOptions {
  url: string;
  method: "GET" | "POST" | "PUT" | "DELETE";
  data?: any;
}

interface resData {
  statusCode: number;
  data: any;
}

const request = (options: httpOptions): Promise<resData> => {
  uni.showLoading({
    title: "玩命加载中。。。",
  });
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseURL}/${options.url}`,
      method: options.method,
      data: options.data,
      header: { Authorization: getToken() },
      success(res: any) {
        uni.hideLoading();
        if (res.statusCode === 200) {
          resolve(res);
        } else if (res.statusCode === 401) {
          uni.showToast({
            title: "没有权限访问接口数据",
            icon: "none",
          });

          uni.navigateTo({
            url: "/pages/login/index",
          });

          return Promise.reject("没有权限访问接口数据");
        } else if (res.statusCode === 202) {
          uni.showToast({
            title: res.data.msg,
            icon: "none",
          });
        }
      },
      fail(error) {
        uni.hideLoading();
        return Promise.reject(error);
      },
    });
  });
};

export default request;
